package tt.dz.egobus.servicemanager.service.impl;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.stereotype.Service;
import tt.dz.egobus.api.managerservice.manager.DistributeDriverTask;
import tt.dz.egobus.api.managerservice.manager.RequestTask;
import tt.dz.egobus.bean.BusinessStatus;
import tt.dz.egobus.cache.service.ExtendCacheService;
import tt.dz.egobus.servicemanager.business.key.BusinessCache;
import tt.dz.egobus.servicemanager.business.point.BusPoint;
import tt.dz.egobus.servicemanager.service.GrabBusinessCacheService;

/**
 * @author Anson
 * @date 17-8-9
 * @name 抢单服务的业务缓存实现类
 * @since 1.0.6
 */
@Service("grabRedisBusinessCacheServiceImpl")
public class GrabRedisBusinessCacheServiceImpl extends RedisBusinessCacheServiceImpl implements GrabBusinessCacheService {

    @Autowired
    @Qualifier("extendsRedisServiceImpl")
    private ExtendCacheService extendCacheService;

    /**
     * @param requestTask          请求信息
     * @param distributeDriverTask 任务分发
     * @param busPoints            当前有效的车地理位置
     * @author Anson
     * @date 17-3-27
     * @name 更新某一个业务请求, 并且设置当前业务状态为抢单状态
     * @since 1.0.3
     */
    @Override
    public void updateBusiness(RequestTask requestTask, DistributeDriverTask distributeDriverTask, BusPoint[] busPoints) {
        if (distributeDriverTask == null || requestTask == null) {
            return;
        }
        BusinessCache.BusinessCacheBuilder businessCacheBuilder = BusinessCache.newBuilder();
        businessCacheBuilder.setBusinessId(distributeDriverTask.getBusinessId())
                .setDrivers(busPoints)
                .setUserId(distributeDriverTask.getUserId())
                .setRequestTask(requestTask)
                .setGrabLimitTimeoutSeconds(distributeDriverTask.getGrabLimitTimeoutSeconds())
                .setLimitTimeoutSeconds(distributeDriverTask.getLimitTimeoutSeconds())
                .setCreateDate(distributeDriverTask.getBusinessCreateTime())
                .setStatus(BusinessStatus.GRAB_BUSINESS);
        BusinessCache businessCache = businessCacheBuilder.builder();
        this.updateBusiness(businessCache);
    }

    @Override
    public boolean doGrabLost(String businessId) {
        this.updateStatus(businessId, BusinessStatus.LOSS_BUSINESS_TIMEOUT);
        return true;
    }

    @Override
    public boolean doGrabTimeout(String businessId) {
        this.updateStatus(businessId, BusinessStatus.GRAB_BUSINESS_TIMEOUT);
        return true;
    }
}
